<template>
  <div class="files-container">
    <a-layout class="files-layout">
      <!-- 左侧分类菜单 -->
      <a-layout-sider theme="light" class="files-sider" width="180">
        <div class="category-menu">
          <div
            class="menu-item"
            :class="{ active: currentCategory === 'all' }"
            @click="handleCategoryClick('all')"
          >
            <img src="@/assets/files/全部.png" class="category-icon" alt="全部" />
            <span>全部</span>
          </div>
          <div
            class="menu-item"
            :class="{ active: currentCategory === 'image' }"
            @click="handleCategoryClick('image')"
          >
            <img src="@/assets/files/图片.png" class="category-icon" alt="图片" />
            <span>图片</span>
          </div>
          <div
            class="menu-item"
            :class="{ active: currentCategory === 'video' }"
            @click="handleCategoryClick('video')"
          >
            <img src="@/assets/files/视频.png" class="category-icon" alt="视频" />
            <span>视频</span>
          </div>
          <div
            class="menu-item"
            :class="{ active: currentCategory === 'audio' }"
            @click="handleCategoryClick('audio')"
          >
            <img src="@/assets/files/音乐.png" class="category-icon" alt="音乐" />
            <span>音乐</span>
          </div>
          <div
            class="menu-item"
            :class="{ active: currentCategory === 'document' }"
            @click="handleCategoryClick('document')"
          >
            <img src="@/assets/files/文档.png" class="category-icon" alt="文档" />
            <span>文档</span>
          </div>
          <div
            class="menu-item"
            :class="{ active: currentCategory === 'other' }"
            @click="handleCategoryClick('other')"
          >
            <img src="@/assets/files/其他.png" class="category-icon" alt="其他" />
            <span>其他</span>
          </div>
        </div>
      </a-layout-sider>

      <!-- 右侧内容区 -->
      <a-layout-content class="files-content">
        <a-card :bordered="false" class="content-card">
          <!-- 顶部操作栏 -->
          <div class="operation-bar">
            <div class="left-operations">
              <a-button type="primary" @click="handleNewFolder"> 新建文件夹 </a-button>
              <a-button type="primary" @click="handleUploadFile"> 上传文件 </a-button>
              <a-popover
                placement="bottom"
                v-model:visible="uploadPopoverVisible"
                trigger="click"
                :overlayStyle="{ width: '400px', padding: 0 }"
              >
                <template #content>
                  <div class="upload-list">
                    <div class="upload-list-header">
                      <span>上传任务</span>
                      <span class="tips">（仅展示最新10条上传任务）</span>
                    </div>
                    <div class="upload-list-content">
                      <template v-if="uploadFileList.length">
                        <div
                          v-for="item in uploadFileList.slice(0, 10)"
                          :key="item.uid"
                          class="upload-item"
                        >
                          <div class="file-name" :title="item.fileName">
                            {{ item.fileName }}
                          </div>
                          <a-progress
                            v-if="item.status === 'uploading'"
                            :percent="item.uploadProgress"
                            size="small"
                          />
                          <div class="upload-status">
                            <span :class="getStatusClass(item.status)">
                              {{ getStatusText(item.status) }}
                            </span>
                            <template v-if="item.status === 'fail'">
                              <a-button type="link" @click="retryUpload(item)"> 重试 </a-button>
                              <a-button type="link" danger @click="removeUploadItem(item)">
                                删除
                              </a-button>
                            </template>
                          </div>
                        </div>
                      </template>
                      <div v-else class="empty-tip">暂无上传任务</div>
                    </div>
                  </div>
                </template>
                <template #default>
                  <a-button type="primary">
                    <template #icon><UploadOutlined /></template>
                    上传列表
                  </a-button>
                </template>
              </a-popover>
              <a-button @click="handleBatchDownload"> 批量下载 </a-button>
              <a-button @click="handleBatchMove"> 批量移动 </a-button>
              <a-button danger @click="handleBatchDelete"> 批量删除 </a-button>
              <a-button type="primary" @click="fetchFileList"> 刷新 </a-button>
            </div>

            <a-input-search
              v-model:value="fileQueryParams.fileNameFuzzy"
              placeholder="搜索文件..."
              style="width: 260px"
              @search="handleFileSearch"
            />
          </div>

          <!-- 修改标题部分 -->
          <div class="files-title">
            <template v-for="(item, index) in pathHistory" :key="item.fileId">
              <span class="folder-path-item" @click="navigateToFolder(item)">{{
                item.fileName
              }}</span>
              <span class="path-separator" v-if="index < pathHistory.length - 1">/</span>
            </template>
          </div>

          <!-- 文件列表 -->
          <a-table
            :columns="fileColumns"
            :data-source="fileList"
            :row-selection="{
              selectedRowKeys: selectedFileKeys,
              onChange: onSelectChange,
            }"
            :row-key="record => record.id"
            :pagination="{
              total: fileTotal,
              current: fileQueryParams.pageNo,
              pageSize: fileQueryParams.pageSize,
              onChange: handleFilePageChange,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: total => `共 ${total} 条`,
            }"
            class="files-table"
            size="middle"
            :scroll="{ y: 'calc(100vh - 250px)' }"
            @row-click="handleRowClick"
          >
            <template #bodyCell="{ column, record }">
              <!-- 图标列 -->
              <template v-if="column.key === 'icon'">
                <div
                  class="file-icon"
                  :class="{
                    'has-cover':
                      record.fileCover && (record.fileType === 1 || record.fileType === 3),
                  }"
                >
                  <!-- 图片和视频文件使用缩略图 -->
                  <template v-if="record.fileType === 3 && record.fileCover">
                    <img :src="record.fileCover" :alt="record.fileName" />
                  </template>
                  <template v-else-if="record.fileType === 1 && record.fileCover">
                    <img :src="record.fileCover" :alt="record.fileName" />
                    <div class="video-overlay">
                      <i class="video-play-icon"></i>
                    </div>
                  </template>
                  <!-- 其他文件使用主题化图标 -->
                  <template v-else>
                    <ThemeFileIcon 
                      :fileType="getFileTypeForIcon(record)" 
                      :fileName="record.fileName"
                      size="medium"
                    />
                  </template>
                </div>
              </template>

              <!-- 文件名列 -->
              <template v-if="column.key === 'name'">
                <span class="file-name-text" @click="handleFileClick(record)">
                  {{ record.fileName }}
                </span>
              </template>

              <!-- 文件大小列 -->
              <template v-if="column.key === 'size'">
                <span>{{ formatSize(record.fileSize) }}</span>
              </template>

              <!-- 修改时间列 -->
              <template v-if="column.key === 'time'">
                <span>{{ formatDate(record.updateTime) }}</span>
              </template>

              <!-- 操作列 -->
              <template v-if="column.key === 'action'">
                <div class="action-cell">
                  <!-- 只有非文件夹才显示下载按钮 -->
                  <a-tooltip v-if="!record.folderType" title="下载">
                    <DownloadOutlined class="action-icon" @click="handleDownload(record)" />
                  </a-tooltip>
                  <a-tooltip title="分享">
                    <ShareAltOutlined class="action-icon" @click="handleShare(record)" />
                  </a-tooltip>
                  <a-tooltip title="移动">
                    <SwapOutlined class="action-icon" @click="handleMove(record)" />
                  </a-tooltip>
                  <a-tooltip title="重命名">
                    <EditOutlined class="action-icon" @click="handleRename(record)" />
                  </a-tooltip>
                  <a-tooltip title="删除">
                    <DeleteOutlined class="action-icon" @click="handleDelete(record)" />
                  </a-tooltip>
                </div>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-layout-content>
    </a-layout>

    <!-- 新建文件夹弹窗 -->
    <a-modal
      v-model:visible="newFolderVisible"
      title="新建文件夹"
      @ok="handleNewFolderSubmit"
      :confirmLoading="newFolderLoading"
      class="custom-modal new-folder-modal"
      okText="确定"
      cancelText="取消"
    >
      <div class="new-folder-content">
        <a-form :model="newFolderForm">
          <a-form-item>
            <div class="folder-icon-wrapper">
              <img :src="folderIcon" alt="文件夹" class="folder-icon" />
            </div>
            <a-input
              v-model:value="newFolderForm.name"
              placeholder="请输入文件夹名称"
              :maxLength="50"
              showCount
              allowClear
              class="folder-input"
              @pressEnter="handleNewFolderSubmit"
            />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

    <!-- 移动文件弹窗 -->
    <a-modal
      v-model:visible="moveVisible"
      title="移动到"
      @ok="handleMoveSubmit"
      :confirmLoading="moveLoading"
      class="move-modal"
      okText="移动到此处"
      cancelText="取消"
      :width="800"
    >
      <div class="move-content">
        <!-- 左侧已选择文件列表 -->
        <div class="selected-files">
          <div class="section-title">已选择的文件</div>
          <div class="selected-file-list">
            <div v-for="file in selectedFiles" :key="file.id" class="selected-file-item">
              <!-- 添加文件图标 -->
              <div
                class="file-icon"
                :class="{
                  'has-cover': file.fileCover && (file.fileType === 1 || file.fileType === 3),
                }"
              >
                <!-- 文件夹 -->
                <img v-if="file.folderType === 1" :src="folderIcon" alt="文件夹" />
                <!-- 图片文件 -->
                <img
                  v-else-if="file.fileType === 3"
                  :src="file.fileCover || imageIcon"
                  :alt="file.fileName"
                />
                <!-- 视频文件 -->
                <template v-else-if="file.fileType === 1">
                  <img :src="file.fileCover || videoIcon" :alt="file.fileName" />
                  <div class="video-overlay" v-if="file.fileCover">
                    <i class="video-play-icon"></i>
                  </div>
                </template>
                <!-- 音频文件 -->
                <img v-else-if="file.fileType === 2" :src="audioIcon" alt="音频" />
                <!-- PDF文件 -->
                <img v-else-if="file.fileType === 4" :src="pdfIcon" alt="PDF" />
                <!-- Word文档 -->
                <img v-else-if="file.fileType === 5" :src="docIcon" alt="Word" />
                <!-- Excel文件 -->
                <img v-else-if="file.fileType === 6" :src="excelIcon" alt="Excel" />
                <!-- 文本文件 -->
                <img v-else-if="file.fileType === 7" :src="txtIcon" alt="文本" />
                <!-- 代码文件 -->
                <img v-else-if="file.fileType === 8" :src="codeIcon" alt="代码" />
                <!-- 压缩文件 -->
                <img v-else-if="file.fileType === 9" :src="zipIcon" alt="压缩包" />
                <!-- 其他文件 -->
                <img v-else :src="otherIcon" alt="其他" />
              </div>
              <span class="file-name">{{ file.fileName }}</span>
            </div>
          </div>
        </div>

        <!-- 右侧文件夹树 -->
        <div class="folder-container">
          <div class="section-title">选择目标文件夹</div>
          <a-tree
            v-model:selectedKeys="selectedFolderKeys"
            v-model:expandedKeys="expandedKeys"
            :treeData="folderTree"
            :fieldNames="{
              title: 'fileName',
              key: 'id',
              children: 'children',
            }"
            @select="onFolderSelect"
            class="folder-tree"
            :selectable="true"
            :blockNode="true"
          >
            <template #title="{ fileName }">
              <span class="tree-node">
                <img :src="folderIcon" class="folder-icon" alt="文件夹" />
                <span class="folder-name">{{ fileName }}</span>
              </span>
            </template>
          </a-tree>
        </div>
      </div>
    </a-modal>

    <!-- 预览弹窗 -->
    <EnhancedPreviewModal
      v-model:visible="previewVisible"
      :file="previewFile"
      @download="() => handleDownload(previewFile)"
    />

    <!-- 重命名弹窗 -->
    <a-modal
      v-model:visible="renameVisible"
      title="重命名"
      @ok="handleRenameSubmit"
      :confirmLoading="renameLoading"
      okText="确定"
      cancelText="取消"
      class="custom-modal"
    >
      <a-form :model="renameForm">
        <a-form-item label="新名称">
          <a-input
            v-model:value="renameForm.name"
            placeholder="请输入新名称"
            :maxLength="50"
            showCount
            allowClear
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 分享弹窗 -->
    <a-modal
      v-model:visible="shareVisible"
      title="分享文件"
      @ok="handleShareSubmit"
      :confirmLoading="shareLoading"
      class="custom-modal"
      okText="生成分享链接"
      cancelText="取消"
    >
      <div class="share-file-info">
        <div class="file-icon">
          <FileOutlined v-if="shareForm.fileName" />
        </div>
        <div class="file-name">{{ shareForm.fileName }}</div>
      </div>

      <a-form :model="shareForm" layout="vertical">
        <a-form-item label="有效期">
          <a-select v-model:value="shareForm.validType" style="width: 100%">
            <a-select-option :value="0">1天</a-select-option>
            <a-select-option :value="1">7天</a-select-option>
            <a-select-option :value="2">30天</a-select-option>
            <a-select-option :value="3">永久有效</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="分享码">
          <a-radio-group v-model:value="shareCodeType" class="share-code-type">
            <a-radio :value="1">系统生成</a-radio>
            <a-radio :value="2">手动输入</a-radio>
          </a-radio-group>

          <div v-if="shareCodeType === 2" class="custom-share-input">
            <input
              v-model="shareForm.code"
              type="text"
              placeholder="请输入分享码"
              maxlength="5"
              class="share-code-input"
            />
            <span class="input-count">{{ shareForm.code.length }}/5</span>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 分享成功弹窗 -->
    <a-modal
      v-model:visible="shareSuccessVisible"
      :footer="null"
      :closable="false"
      width="800px"
      class="share-success-modal"
      :maskClosable="false"
    >
      <div class="share-success-header">
        <CheckCircleFilled class="success-icon" />
        <span class="success-text">分享成功</span>
      </div>

      <div class="share-success-content">
        <!-- 文件信息区域 -->
        <div class="file-info-section">
          <div class="file-icon">
            <!-- 文件夹 -->
            <img v-if="shareForm.folderType === 1" :src="folderIcon" alt="文件夹" />
            <!-- 图片文件 -->
            <img
              v-else-if="shareForm.fileType === 3"
              :src="shareForm.fileCover || imageIcon"
              :alt="shareForm.fileName"
            />
            <!-- 视频文件 -->
            <template v-else-if="shareForm.fileType === 1">
              <img :src="shareForm.fileCover || videoIcon" :alt="shareForm.fileName" />
              <div class="video-overlay" v-if="shareForm.fileCover">
                <i class="video-play-icon"></i>
              </div>
            </template>
            <!-- 音频文件 -->
            <img v-else-if="shareForm.fileType === 2" :src="audioIcon" alt="音频" />
            <!-- PDF文件 -->
            <img v-else-if="shareForm.fileType === 4" :src="pdfIcon" alt="PDF" />
            <!-- Word文档 -->
            <img v-else-if="shareForm.fileType === 5" :src="docIcon" alt="Word" />
            <!-- Excel文件 -->
            <img v-else-if="shareForm.fileType === 6" :src="excelIcon" alt="Excel" />
            <!-- 文本文件 -->
            <img v-else-if="shareForm.fileType === 7" :src="txtIcon" alt="文本" />
            <!-- 代码文件 -->
            <img v-else-if="shareForm.fileType === 8" :src="codeIcon" alt="代码" />
            <!-- 压缩文件 -->
            <img v-else-if="shareForm.fileType === 9" :src="zipIcon" alt="压缩包" />
            <!-- 其他文件 -->
            <img v-else :src="otherIcon" alt="其他" />
          </div>
          <div class="file-name">{{ shareForm.fileName }}</div>
        </div>

        <!-- 分享信息列表 -->
        <div class="share-info-list">
          <div class="share-info-item">
            <span class="info-label">分享链接</span>
            <div class="info-value">
              <span class="text-content">{{ shareUrl }}</span>
              <a-button type="link" class="copy-btn" @click="copyShareUrl">
                <template #icon><CopyOutlined /></template>
                复制
              </a-button>
            </div>
          </div>

          <div class="share-info-item">
            <span class="info-label">分享码</span>
            <div class="info-value">
              <span class="text-content">{{ shareForm.code }}</span>
              <a-button type="link" class="copy-btn" @click="copyShareCode">
                <template #icon><CopyOutlined /></template>
                复制
              </a-button>
            </div>
          </div>

          <div class="share-info-item">
            <span class="info-label">分享时间</span>
            <div class="info-value">
              <span>{{ shareTime }}</span>
            </div>
          </div>

          <div class="share-info-item">
            <span class="info-label">过期时间</span>
            <div class="info-value">
              <span>{{ expireTime }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="share-success-footer">
        <a-button type="primary" @click="shareSuccessVisible = false"> 确定 </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { message, Modal } from 'ant-design-vue'
  import {
    FileOutlined,
    UploadOutlined,
    DownloadOutlined,
    SwapOutlined,
    DeleteOutlined,
    EditOutlined,
    ShareAltOutlined,
    CheckCircleFilled,
    CopyOutlined,
  } from '@ant-design/icons-vue'
  import { formatDate } from '@/utils/date'
  import {
    uploadFileUsingPost,
    getFileListUsingGet,
    deleteFileUsingPost,
    renameFileUsingPost,
    createFolderUsingPost,
    loadAllFolderUsingPost,
    changeFileFolderUsingPost
  } from '@/api/wenjianmokuai'
  import { shareFileUsingPost } from '@/api/wenjiangongxiangjiekou'
  import folderIcon from '@/assets/files/文件夹.png'
  import imageIcon from '@/assets/files/图片.png'
  import videoIcon from '@/assets/files/视频.png'
  import audioIcon from '@/assets/files/音乐.png'
  import pdfIcon from '@/assets/files/pdf.png'
  import docIcon from '@/assets/files/doc.png'
  import excelIcon from '@/assets/files/excel.png'
  import txtIcon from '@/assets/files/txt.png'
  import codeIcon from '@/assets/files/code.png'
  import zipIcon from '@/assets/files/zip.png'
  import otherIcon from '@/assets/files/其他.png'
  import EnhancedPreviewModal from '@/components/EnhancedPreviewModal.vue'
  import ThemeFileIcon from '@/components/ThemeFileIcon.vue'
  import SparkMD5 from 'spark-md5/spark-md5.min'

  // 当前选中的分类
  const currentCategory = ref('all')

  // 文件列表相关
  const fileQueryParams = reactive({
    pageNo: 1,
    pageSize: 10,
    fileNameFuzzy: '',
    fileCategory: '', // 修改为 fileCategory
    filePid: '0', // 默认根目录
  })

  // 添加路径历史相关的状态
  const pathHistory = ref([{ fileId: '0', fileName: '全部文件' }])

  const fileTotal = ref(0)
  const fileColumns = ref([
    {
      title: '',
      dataIndex: 'icon',
      key: 'icon',
      width: '48px',
    },
    {
      title: '文件名',
      dataIndex: 'fileName',
      key: 'name',
      width: 'auto',
      ellipsis: true,
    },
    {
      title: '大小',
      dataIndex: 'fileSize',
      key: 'size',
      width: '120px',
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'time',
      width: '180px',
    },
    {
      title: '操作',
      key: 'action',
      width: '180px',
      fixed: 'right',
    },
  ])

  const fileList = ref([])
  const selectedFileKeys = ref<string[]>([])
  const selectedFiles = ref<any[]>([])
  const currentFolder = ref<any>(null)

  // 添加一个展开的文件夹ID数组
  const expandedKeys = ref<string[]>([])

  // 文件大小格式化
  const formatSize = (size: string | number) => {
    if (!size) return '0 B'

    // 如果是字符串且包含单位，直接返回
    if (typeof size === 'string') {
      if (/^[\d.]+\s*[KMGT]?B$/i.test(size.trim())) {
        return size.trim()
      }
      // 如果是纯数字字符串，转为数字处理
      size = parseFloat(size)
    }

    // 处理纯数字
    if (typeof size === 'number') {
      if (size < 1024) {
        return `${size} B`
      } else if (size < 1024 * 1024) {
        return `${(size / 1024).toFixed(2)} KB`
      } else if (size < 1024 * 1024 * 1024) {
        return `${(size / (1024 * 1024)).toFixed(2)} MB`
      } else {
        return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`
      }
    }

    return '0 B'
  }

  // 选择变化处理
  const onSelectChange = (selectedRowKeys: string[], selectedRows: any[]) => {
    selectedFileKeys.value = selectedRowKeys
    selectedFiles.value = selectedRows
  }

  // 获取文件列表
  const fetchFileList = async () => {
    try {
      const res = await getFileListUsingGet({
        pageNo: fileQueryParams.pageNo.toString(),
        pageSize: fileQueryParams.pageSize.toString(),
        fileNameFuzzy: fileQueryParams.fileNameFuzzy,
        fileCategory: fileQueryParams.fileCategory,
        filePid: fileQueryParams.filePid,
      })

      if (res.data?.code === 200) {
        // 更新文件列表
        fileList.value = (res.data.data.list || []).map(file => {
          return {
            ...file,
            id: file.fileId,
            fileSize: file.fileSize, // 直接使用原始值，不做转换
            updateTime: file.lastUpdateTime || file.createTime,
            isFolder: file.folderType === 1,
          }
        })

        // 更新总数
        fileTotal.value = parseInt(res.data.data.totalCount) || 0

        // 更新当前文件夹信息
        if (res.data.data.currentFolder) {
          currentFolder.value = {
            ...res.data.data.currentFolder,
            filePath: res.data.data.currentFolder.filePath || '',
            filePathIds: (res.data.data.currentFolder.filePathIds || '').split(',').filter(Boolean),
          }
        }
      } else {
        message.error(res.data?.message || '获取文件列表失败')
      }
    } catch (error) {
      console.error('获取文件列表错误:', error)
      message.error('获取文件列表失败')
    }
  }

  // 获取分类对应的值
  const getCategoryValue = (category: string) => {
    const categoryMap = {
      all: '', // 全部分类，参数为空
      video: '1', // 视频分类
      audio: '2', // 音频分类
      image: '3', // 图片分类
      document: '4', // 文档分类
      other: '5', // 其他分类
    }
    return categoryMap[category] || ''
  }

  // 根据文件记录获取图标类型
  const getFileTypeForIcon = (record: any) => {
    if (record.folderType === 1) {
      return 'folder'
    }
    
    // 根据文件类型ID映射
    const typeMap = {
      1: 'video',    // 视频
      2: 'audio',    // 音频
      3: 'image',    // 图片
      4: 'pdf',      // PDF
      5: 'document', // Word文档
      6: 'document', // Excel文档
      7: 'document', // 文本文件
      8: 'code',     // 代码文件
      9: 'archive',  // 压缩文件
    }
    
    return typeMap[record.fileType] || 'default'
  }

  // 页码变化处理
  const handleFilePageChange = (page: number, pageSize?: number) => {
    fileQueryParams.pageNo = page
    if (pageSize) {
      fileQueryParams.pageSize = pageSize
    }
    fetchFileList()
  }

  // 分类点击处理
  const handleCategoryClick = async (category: string) => {
    currentCategory.value = category
    fileQueryParams.pageNo = 1
    fileQueryParams.fileCategory = getCategoryValue(category) // 修改为 fileCategory
    await fetchFileList() // 等待数据获取完成
    fileList.value = [...fileList.value] // 强制更新视图
  }

  // 搜索处理
  const handleFileSearch = () => {
    fileQueryParams.pageNo = 1
    fileQueryParams.fileNameFuzzy = fileQueryParams.fileNameFuzzy
    fetchFileList()
  }

  // 新建文件夹相关
  const newFolderVisible = ref(false)
  const newFolderLoading = ref(false)
  const newFolderForm = reactive({
    name: '',
  })

  const handleNewFolder = () => {
    newFolderForm.name = ''
    newFolderVisible.value = true
  }

  const handleNewFolderSubmit = async () => {
    if (!newFolderForm.name) {
      message.warning('请输入文件夹名称')
      return
    }

    newFolderLoading.value = true
    try {
      const res = await createFolderUsingPost({
        fileName: newFolderForm.name,
        filePid: fileQueryParams.filePid, // 使用当前所在文件夹的ID
      })
      if (res.data?.code === 200) {
        message.success('创建成功')
        newFolderVisible.value = false
        fetchFileList()
      }
    } catch {
      message.error('创建失败')
    } finally {
      newFolderLoading.value = false
    }
  }

  // 上传列表相关
  const uploadFileList = ref([])
  const uploadPopoverVisible = ref(false)

  // 计算文件的MD5
  const computeFileMD5 = file => {
    return new Promise((resolve, reject) => {
      const blobSlice =
        File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
      const chunkSize = 2097152 // 每次读取 2MB
      const chunks = Math.ceil(file.size / chunkSize)
      let currentChunk = 0
      const spark = new SparkMD5.ArrayBuffer()
      const fileReader = new FileReader()

      fileReader.onload = function (e) {
        spark.append(e.target.result)
        currentChunk++

        if (currentChunk < chunks) {
          loadNext()
        } else {
          const md5 = spark.end()
          resolve(md5)
        }
      }

      fileReader.onerror = function (e) {
        reject(e)
      }

      function loadNext() {
        const start = currentChunk * chunkSize
        const end = start + chunkSize >= file.size ? file.size : start + chunkSize
        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
      }

      loadNext()
    })
  }

  // 添加文件到上传列表
  const addFile = async (file, filePid = '0') => {
    if (!file) {
      console.error('文件对象无效')
      return
    }

    // 检查是否已存在相同文件
    const existingFile = uploadFileList.value.find(
      item => item.fileName === file.name && item.status !== 'fail'
    )

    if (existingFile) {
      message.warning(`文件 ${file.name} 已在上传列表中`)
      return
    }

    // 计算文件MD5
    const fileMd5 = await computeFileMD5(file)

    const fileItem = {
      uid: Date.now() + Math.random().toString(36).slice(2),
      file: file,
      fileName: file.name,
      fileSize: file.size,
      fileType: file.type,
      filePid: filePid,
      fileMd5: fileMd5,
      status: 'init',
      uploadProgress: 0,
      errorMsg: null,
      chunkIndex: 0,
      chunks: Math.ceil(file.size / (2 * 1024 * 1024)), // 2MB per chunk
      fileId: null,
    }

    uploadFileList.value.unshift(fileItem)
    startUpload(fileItem)
  }

  // 开始上传文件
  const startUpload = async fileItem => {
    try {
      if (!fileItem || !fileItem.file) {
        console.error('文件对象无效')
        return
      }

      const chunkSize = 2 * 1024 * 1024 // 2MB per chunk
      const totalChunks = fileItem.chunks
      const file = fileItem.file

      fileItem.status = 'uploading'

      for (let chunkIndex = fileItem.chunkIndex; chunkIndex < totalChunks; chunkIndex++) {
        const start = chunkIndex * chunkSize
        const end = Math.min(start + chunkSize, file.size)
        const chunk = file.slice(start, end)

        try {
          const result = await uploadFileUsingPost({
            file: chunk,
            fileName: fileItem.fileName,
            fileSize: fileItem.fileSize,
            fileMd5: fileItem.fileMd5,
            chunkIndex: chunkIndex,
            chunks: totalChunks,
            fileId: fileItem.fileId || '',
            filePid: fileItem.filePid || '0',
          })

          if (result.data?.code === 200) {
            fileItem.fileId = result.data.data.fileId
            fileItem.chunkIndex = chunkIndex + 1
            fileItem.uploadProgress = Math.round(((chunkIndex + 1) * 100) / totalChunks)

            if (chunkIndex === totalChunks - 1) {
              fileItem.status = 'upload_finish'
              fileItem.uploadProgress = 100
              message.success('上传成功')
              fetchFileList()
              break
            }
          } else {
            fileItem.status = 'fail'
            fileItem.errorMsg = result.data?.message || '上传失败'
            message.warning(result.data?.message || '上传失败')
            break
          }
        } catch (error) {
          console.error('分片上传失败:', error)
          fileItem.status = 'fail'
          fileItem.errorMsg = '上传失败: ' + (error.message || '未知错误')
          message.error('上传失败，请稍后重试')
          break
        }
      }
    } catch (error) {
      console.error('文件上传失败:', error)
      if (fileItem) {
        fileItem.status = 'fail'
        fileItem.errorMsg = '上传失败: ' + (error.message || '未知错误')
      }
      message.error('上传失败，请稍后重试')
    }
  }

  // 重试上传
  const retryUpload = fileItem => {
    if (!fileItem || !fileItem.file) {
      message.error('文件已不存在，无法重试')
      return
    }
    startUpload(fileItem)
  }

  // 移除上传项
  const removeUploadItem = fileItem => {
    if (!fileItem || !fileItem.uid) {
      console.error('无效的文件项')
      return
    }

    const index = uploadFileList.value.findIndex(item => item.uid === fileItem.uid)
    if (index > -1) {
      uploadFileList.value.splice(index, 1)
      message.success('已移除文件')
    }
  }

  // 获取状态样式类
  const getStatusClass = status => {
    const classes = {
      init: 'status-init',
      uploading: 'status-uploading',
      upload_finish: 'status-success',
      upload_seconds: 'status-success',
      fail: 'status-error',
      emptyfile: 'status-error',
    }
    return classes[status] || ''
  }

  // 获取状态文本
  const getStatusText = status => {
    const texts = {
      init: '准备上传',
      uploading: '上传中',
      upload_finish: '上传完成',
      upload_seconds: '秒传完成',
      fail: '上传失败',
      emptyfile: '文件为空',
    }
    return texts[status] || status
  }

  // 修改文件上传处理
  const handleUploadFile = () => {
    const input = document.createElement('input')
    input.type = 'file'
    input.multiple = true
    input.onchange = async e => {
      const files = Array.from(e.target.files || [])
      if (!files?.length) return

      for (const file of files) {
        await addFile(file, fileQueryParams.filePid)
      }

      // 清空 input
      e.target.value = ''
    }
    input.click()
  }

  // 单个文件操作
  const handleDownload = async (record: any) => {
    try {
      if (!record.filePath) {
        message.error('文件路径不存在')
        return
      }
      window.open(record.filePath)
    } catch (error) {
      console.error('下载错误:', error)
      message.error('下载失败：' + (error?.message || '未知错误'))
    }
  }

  // 批量下载处理
  const handleBatchDownload = async () => {
    if (selectedFileKeys.value.length === 0) {
      message.warning('请选择要下载的文件')
      return
    }

    try {
      selectedFiles.value.forEach(file => {
        if (file.filePath) {
          window.open(file.filePath)
        }
      })
    } catch (error) {
      console.error('批量下载错误:', error)
      message.error('批量下载失败：' + (error?.message || '未知错误'))
    }
  }

  // 移动文件相关
  const moveVisible = ref(false)
  const moveLoading = ref(false)
  const selectedFolderKeys = ref<string[]>([])
  const folderTree = ref([])

  // 加载文件夹列表
  const loadFolderList = async () => {
    try {
      const res = await loadAllFolderUsingPost({
        filePid: '0', // 初始加载根目录
        currentFileIds: selectedFileKeys.value.join(','), // 当前选中的文件ID
      })

      if (res.data?.code === 200) {
        // 处理返回的数据，转换成树形结构所需的格式
        folderTree.value = (res.data.data || []).map(item => ({
          ...item,
          id: item.fileId,
          fileName: item.fileName,
          key: item.fileId,
          children: [],
        }))
      } else {
        message.error(res.data?.message || '加载文件夹列表失败')
      }
    } catch (error) {
      console.error('加载文件夹列表错误:', error)
      message.error('加载文件夹列表失败')
    }
  }

  const handleBatchMove = () => {
    if (selectedFileKeys.value.length === 0) {
      message.warning('请选择要移动的文件')
      return
    }
    // 重置选中的文件夹
    selectedFolderKeys.value = []
    // 加载文件夹列表
    loadFolderList()
    moveVisible.value = true
  }

  const onFolderSelect = async (keys: string[], info: any) => {
    selectedFolderKeys.value = keys
    if (keys.length > 0 && info?.node) {
      // 将当前点击的文件夹ID添加到展开列表中
      if (!expandedKeys.value.includes(info.node.id)) {
        expandedKeys.value.push(info.node.id)
      }

      try {
        const res = await loadAllFolderUsingPost({
          filePid: info.node.id,
          currentFileIds: selectedFileKeys.value.join(','),
        })

        if (res.data?.code === 200) {
          const updateTreeData = (list: any[], key: string, children: any[]): any[] => {
            return list.map(node => {
              if (node.id === key) {
                return {
                  ...node,
                  children: children.map(child => ({
                    ...child,
                    id: child.fileId,
                    fileName: child.fileName,
                    key: child.fileId,
                  })),
                }
              }
              if (node.children) {
                return {
                  ...node,
                  children: updateTreeData(node.children, key, children),
                }
              }
              return node
            })
          }

          folderTree.value = updateTreeData(folderTree.value, info.node.id, res.data.data || [])
        }
      } catch (error) {
        console.error('加载文件夹列表错误:', error)
        message.error('加载文件夹列表失败')
      }
    }
  }

  const handleMoveSubmit = async () => {
    if (selectedFolderKeys.value.length === 0) {
      message.warning('请选择目标文件夹')
      return
    }

    moveLoading.value = true
    try {
      const res = await changeFileFolderUsingPost({
        fileIds: selectedFileKeys.value.join(','),
        filePid: selectedFolderKeys.value[0],
      })
      if (res.data?.code === 200) {
        message.success('移动成功')
        moveVisible.value = false
        fetchFileList()
        // 清空选中状态
        selectedFileKeys.value = []
        selectedFiles.value = []
      } else {
        message.error(res.data?.message || '移动失败')
      }
    } catch (error) {
      console.error('移动文件错误:', error)
      message.error('移动失败')
    } finally {
      moveLoading.value = false
    }
  }

  const handleMove = (record: any) => {
    selectedFileKeys.value = [record.id]
    selectedFiles.value = [record]
    handleBatchMove()
  }

  // 批量删除处理
  const handleBatchDelete = async () => {
    if (selectedFileKeys.value.length === 0) {
      message.warning('请选择要删除的文件')
      return
    }
  }

  // 单个文件删除
  const handleDelete = async (record: any) => {
    try {
      const res = await deleteFileUsingPost({
        fileIds: record.id,
      })
      if (res.data?.code === 200) {
        message.success('删除成功')
        fetchFileList()
      }
    } catch {
      message.error('删除失败')
    }
  }

  // 重命名相关
  const renameVisible = ref(false)
  const renameLoading = ref(false)
  const renameForm = reactive({
    name: '',
    fileId: '',
    filePid: '',
    extension: '', // 添加扩展名字段
  })

  const handleRename = (record: any) => {
    // 分离文件名和扩展名
    const lastDotIndex = record.fileName.lastIndexOf('.')
    if (lastDotIndex > -1) {
      renameForm.name = record.fileName.substring(0, lastDotIndex)
      renameForm.extension = record.fileName.substring(lastDotIndex)
    } else {
      renameForm.name = record.fileName
      renameForm.extension = ''
    }
    renameForm.fileId = record.id
    renameForm.filePid = fileQueryParams.filePid
    renameVisible.value = true
  }

  const handleRenameSubmit = async () => {
    if (!renameForm.name) {
      message.warning('请输入新名称')
      return
    }

    renameLoading.value = true
    try {
      const res = await renameFileUsingPost({
        fileId: renameForm.fileId,
        fileName: renameForm.name + renameForm.extension, // 发送请求时拼接扩展名
        filePid: renameForm.filePid,
      })
      if (res.data?.code === 200) {
        message.success('重命名成功')
        renameVisible.value = false
        fetchFileList()
      } else {
        message.error(res.data?.message || '重命名失败')
      }
    } catch {
      message.error('重命名失败')
    } finally {
      renameLoading.value = false
    }
  }

  // 分享相关
  const shareVisible = ref(false)
  const shareLoading = ref(false)
  const shareCodeType = ref(1) // 1: 系统生成, 2: 手动输入
  const shareSuccessVisible = ref(false)
  const shareUrl = ref('')
  const shareTime = ref('')
  const expireTime = ref('')

  // 修改shareForm的定义
  const shareForm = reactive({
    fileId: '',
    fileName: '',
    validType: 1,
    code: '',
    fileType: 0,
    folderType: 0,
    fileCover: '',
  })

  // 处理分享
  const handleShare = (record: any) => {
    // 设置基本信息
    shareForm.fileId = record.fileId || record.id
    shareForm.fileName = record.fileName
    shareForm.validType = 1
    shareForm.code = ''

    // 设置文件类型信息
    shareForm.fileType = parseInt(record.fileType) || 0
    shareForm.folderType = parseInt(record.folderType) || 0
    shareForm.fileCover = record.fileCover || ''

    // 重置分享码类型为系统生成
    shareCodeType.value = 1
    // 显示分享弹窗
    shareVisible.value = true
  }

  // 提交分享
  const handleShareSubmit = async () => {
    if (shareCodeType.value === 2 && !shareForm.code) {
      message.warning('请输入分享码')
      return
    }

    // 如果是系统生成，将code设为空字符串
    if (shareCodeType.value === 1) {
      shareForm.code = ''
    }

    shareLoading.value = true
    try {
      const res = await shareFileUsingPost(shareForm)
      if (res.data?.code === 200) {
        message.success('分享成功')
        shareVisible.value = false

        // 更新分享信息
        shareUrl.value = `http://localhost:1111/s/${res.data.data.shareId}`
        shareTime.value = res.data.data.shareTime
        expireTime.value = res.data.data.expireTime
        shareForm.code = res.data.data.code

        // 显示分享成功弹窗
        shareSuccessVisible.value = true
      } else {
        message.error(res.data?.message || '分享失败')
      }
    } catch {
      message.error('分享失败')
    } finally {
      shareLoading.value = false
    }
  }

  // 获取文件图标的辅助函数
  const getFileIcon = (fileType: number, fileCover?: string) => {
    if (fileType === 3 && fileCover) return fileCover // 图片且有封面
    if (fileType === 1 && fileCover) return fileCover // 视频且有封面

    const iconMap = {
      1: videoIcon, // 视频
      2: audioIcon, // 音频
      3: imageIcon, // 图片
      4: pdfIcon, // PDF
      5: docIcon, // Word
      6: excelIcon, // Excel
      7: txtIcon, // 文本
      8: codeIcon, // 代码
      9: zipIcon, // 压缩包
    }
    return iconMap[fileType] || otherIcon
  }

  // 处理文件预览
  const previewVisible = ref(false)
  const previewFile = ref({
    fileName: '',
    fileType: 0,
    fileSize: 0,
    fileId: '',
    fileCover: '',
    fileUrl: '',
  })

  const handlePreview = async record => {
    try {
      console.log('预览文件信息:', record)

      // 确保有文件路径
      if (!record.filePath) {
        message.error('文件路径不存在')
        return
      }

      // 获取文件扩展名
      const ext = record.fileName?.split('.')?.pop()?.toLowerCase()

      // 定义可预览的文件类型
      const previewableTypes = {
        // 图片
        jpg: true,
        jpeg: true,
        png: true,
        gif: true,
        webp: true,
        // 视频
        mp4: true,
        webm: true,
        // 音频
        mp3: true,
        wav: true,
        // 文档
        pdf: true,
        // 文本
        txt: true,

        docx: true,
      }

      // 如果是不可预览的文件类型
      if (!previewableTypes[ext]) {
        Modal.confirm({
          title: '无法预览',
          content: '当前文件类型暂不支持预览，是否下载到本地查看？',
          okText: '下载',
          cancelText: '取消',
          onOk: () => handleDownload(record),
        })
        return
      }

      // 设置预览文件信息
      previewFile.value = {
        fileName: record.fileName,
        fileType: parseInt(record.fileType) || 0,
        fileSize: record.fileSize,
        fileId: record.fileId || record.id,
        fileCover: record.fileCover,
        fileUrl: record.filePath,
      }

      console.log('设置预览文件信息:', previewFile.value)
      previewVisible.value = true
    } catch (error) {
      console.error('预览错误:', error)
      message.error('预览失败：' + (error?.message || '未知错误'))
    }
  }

  // 修改文件点击处理
  const handleFileClick = async record => {
    if (record.folderType === 1) {
      enterFolder(record)
    } else {
      handlePreview(record)
    }
  }

  // 修改行点击处理
  const handleRowClick = (row, column, event) => {
    // 如果点击的是文件名列，不进行文件夹导航
    if (column.property === 'fileName') {
      return
    }

    // 如果是文件夹，进行导航
    if (row.folderType === 1) {
      enterFolder(row)
    }
  }

  const copyToClipboard = async (text: string, successMessage: string) => {
    try {
      await navigator.clipboard.writeText(text)
      message.success(successMessage)
    } catch {
      message.error('复制失败，请手动复制')
    }
  }

  const copyShareUrl = () => {
    copyToClipboard(shareUrl.value, '分享链接已复制到剪贴板')
  }

  const copyShareCode = () => {
    copyToClipboard(shareForm.code, '分享码已复制到剪贴板')
  }

  // 进入文件夹时更新路径
  const enterFolder = folder => {
    if (folder.folderType === 1) {
      // 更新当前文件夹ID
      fileQueryParams.filePid = folder.fileId
      // 添加到路径历史
      pathHistory.value.push({
        fileId: folder.fileId,
        fileName: folder.fileName,
      })
      fileQueryParams.pageNo = 1
      fetchFileList()
    }
  }

  // 导航到指定文件夹
  const navigateToFolder = async folder => {
    // 找到点击的文件夹在路径中的位置
    const index = pathHistory.value.findIndex(item => item.fileId === folder.fileId)
    if (index !== -1) {
      // 更新当前文件夹ID
      fileQueryParams.filePid = folder.fileId
      // 截取到点击的位置
      pathHistory.value = pathHistory.value.slice(0, index + 1)
      fileQueryParams.pageNo = 1
      await fetchFileList()
    }
  }

  // 初始化
  onMounted(async () => {
    await fetchFileList()
  })
</script>

<style scoped>
  .files-container {
    height: 100%;
    background: var(--theme-surface);
    transition: all 0.3s ease;
  }

  .files-layout {
    height: calc(100vh - 64px);
    background: var(--theme-surface);
    display: flex;
    transition: all 0.3s ease;
  }

  .files-sider {
    background: var(--theme-surface);
    border-right: 1px solid var(--theme-border);
    height: 100%;
    position: fixed;
    width: 180px;
    transition: all 0.3s ease;
  }

  .category-menu {
    padding: 16px 0;
    border-right: none;
    height: 100%;
  }

  .menu-item {
    display: flex;
    align-items: center;
    padding: 12px 20px;
    margin-bottom: 8px;
    cursor: pointer;
    transition: all 0.3s;
    border-radius: 8px;
    margin: 4px 12px;
  }

  .menu-item:hover {
    background: var(--theme-background);
  }

  .menu-item.active {
    background: var(--theme-background);
    color: var(--theme-primary);
  }

  .menu-item.active span {
    color: var(--theme-primary);
    font-weight: 500;
  }

  .category-icon {
    width: 20px;
    height: 20px;
    margin-right: 8px;
    object-fit: contain;
  }

  .menu-item span {
    font-size: 14px;
    color: var(--theme-text);
    transition: color 0.3s ease;
  }

  .files-content {
    padding: 0;
    margin-left: 180px;
    background: var(--theme-surface);
    min-height: 100%;
    flex: 1;
    transition: all 0.3s ease;
  }

  .content-card {
    background: var(--theme-surface);
    border-radius: 0;
    box-shadow: none;
    height: 100%;
    display: flex;
    flex-direction: column;
    transition: all 0.3s ease;
  }

  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background: var(--theme-surface);
    border-bottom: 1px solid var(--theme-border);
    transition: all 0.3s ease;
  }

  .folder-navigation {
    padding: 16px 24px;
    border-bottom: 1px solid var(--theme-border);
    transition: all 0.3s ease;
  }

  .breadcrumb-item {
    color: var(--theme-textSecondary);
    cursor: pointer;
    transition: all 0.3s;
  }

  .breadcrumb-item:hover {
    color: var(--theme-primary);
  }

  .operation-buttons {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .left-operations {
    display: flex;
    gap: 12px;
  }

  .operation-icon {
    width: 16px;
    height: 16px;
    margin-right: 4px;
  }

  :deep(.ant-btn) {
    display: flex;
    align-items: center;
    height: 32px;
    padding: 0 16px;
    font-size: 14px;
    border-radius: 4px;
  }

  .search-input {
    width: 240px;
  }

  :deep(.ant-input-search .ant-input) {
    border-radius: 4px;
    font-size: 14px;
  }

  :deep(.ant-input-search .ant-input-group-addon) {
    display: none;
  }

  .files-table {
    flex: 1;
    padding: 0;
    display: flex;
    flex-direction: column;
  }

  :deep(.ant-table-wrapper) {
    flex: 1;
  }

  :deep(.ant-table) {
    background: transparent;
  }

  :deep(.ant-table-row) {
    height: 52px;
  }

  :deep(.ant-table-row:hover) {
    background-color: var(--theme-background);
  }

  :deep(.ant-table-cell) {
    padding: 0 12px !important;
    border-bottom: 1px solid var(--theme-border) !important;
    vertical-align: middle;
  }

  .file-icon {
    width: 32px;
    height: 32px;
    border-radius: 4px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--theme-background);
    position: relative;
    transition: all 0.3s ease;
  }

  .file-icon img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .file-icon.has-cover img {
    object-fit: cover;
  }

  .video-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .video-play-icon {
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 8px 0 8px 12px;
    border-color: transparent transparent transparent #ffffff;
  }

  .file-name {
    flex: 1;
    font-size: 14px;
    color: var(--theme-text);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 1.5;
    transition: color 0.3s ease;
  }

  .action-cell {
    display: flex;
    gap: 16px;
    padding-right: 8px;
    justify-content: flex-end;
  }

  :deep(.ant-table-row:hover) .action-cell {
    opacity: 1;
  }

  .action-icon {
    font-size: 16px;
    cursor: pointer;
    color: var(--theme-textSecondary);
    transition: all 0.2s;
  }

  .action-icon:hover {
    color: var(--theme-primary);
    transform: scale(1.1);
  }

  :deep(.ant-pagination) {
    margin: 16px 0 !important;
    padding: 0 16px;
  }



  .custom-modal {
    :deep(.ant-modal-content) {
      background: var(--theme-background);
      border-radius: 12px;
      box-shadow: 0 8px 24px var(--theme-shadow);
    }

    :deep(.ant-modal-header) {
      background: var(--theme-background);
      border-bottom: 1px solid var(--theme-border);
    }

    :deep(.ant-modal-title) {
      color: var(--theme-text);
      font-weight: 600;
      font-size: 16px;
    }

    :deep(.ant-modal-close) {
      color: var(--theme-textSecondary);
    }

    :deep(.ant-modal-close:hover) {
      color: var(--theme-text);
    }

    :deep(.ant-modal-body) {
      background: var(--theme-background);
      color: var(--theme-text);
    }

    :deep(.ant-form-item-label > label) {
      color: var(--theme-text) !important;
      font-weight: 600 !important;
      font-size: 14px !important;
    }

    :deep(.ant-select) {
      background: var(--theme-surface) !important;
    }

    :deep(.ant-select-selector) {
      background: var(--theme-surface) !important;
      border-color: var(--theme-border) !important;
      color: var(--theme-text) !important;
      border-radius: 6px !important;
    }

    :deep(.ant-select-focused .ant-select-selector) {
      border-color: var(--theme-primary) !important;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
    }

    :deep(.ant-select-selection-item) {
      color: var(--theme-text) !important;
    }

    :deep(.ant-radio-wrapper) {
      color: var(--theme-text) !important;
      font-weight: 500 !important;
      font-size: 14px !important;
    }

    :deep(.ant-radio-inner) {
      border-color: var(--theme-border) !important;
      background: var(--theme-surface) !important;
    }

    :deep(.ant-radio-checked .ant-radio-inner) {
      border-color: var(--theme-primary) !important;
    }

    :deep(.ant-radio-inner::after) {
      background: var(--theme-primary) !important;
    }

    :deep(.ant-modal-footer) {
      background: var(--theme-background);
      border-top: 1px solid var(--theme-border);
    }

    :deep(.ant-btn) {
      border-radius: 6px;
      height: 36px;
      padding: 0 16px;
      font-size: 14px;
    }

    :deep(.ant-btn-primary) {
      background: var(--theme-primary);
      border-color: var(--theme-primary);
      color: white;
    }

    :deep(.ant-btn-primary:hover) {
      background: var(--theme-secondary);
      border-color: var(--theme-secondary);
    }

    :deep(.ant-btn-default) {
      background: var(--theme-surface);
      border-color: var(--theme-border);
      color: var(--theme-text);
    }

    :deep(.ant-btn-default:hover) {
      border-color: var(--theme-primary);
      color: var(--theme-primary);
    }
  }

  .move-modal {
    :deep(.ant-modal-content) {
      border-radius: 8px;
      overflow: hidden;
    }

    :deep(.ant-modal-header) {
      margin: 0;
      padding: 16px 24px;
      border-bottom: 1px solid #f0f0f0;
    }

    :deep(.ant-modal-body) {
      padding: 24px;
      max-height: calc(90vh - 110px);
      overflow-y: auto;
    }

    :deep(.ant-modal-footer) {
      margin: 0;
      padding: 16px 24px;
      border-top: 1px solid #f0f0f0;
    }
  }

  .move-content {
    display: flex;
    gap: 24px;
    height: 500px; /* 将高度从 400px 改为 500px */
  }

  .selected-files {
    flex: 1;
    background: #f5f7fa;
    padding: 16px;
    border-radius: 4px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .selected-file-list {
    flex: 1;
    overflow-y: auto;
    padding-right: 8px;
  }

  .selected-file-item {
    display: flex;
    align-items: center;
    padding: 8px;
    border-radius: 4px;
    margin-bottom: 8px;
    background: #fff;
    gap: 12px;
  }

  .selected-file-item .file-icon {
    width: 24px;
    height: 24px;
    flex-shrink: 0;
  }

  .selected-file-item .file-icon img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .selected-file-item .file-name {
    flex: 1;
    font-size: 14px;
    color: #333;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .folder-container {
    flex: 1;
    background: #f5f7fa;
    padding: 16px;
    border-radius: 4px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .folder-tree {
    flex: 1;
    background: #fff;
    border-radius: 4px;
    padding: 8px;
    overflow-y: auto;
  }

  .section-title {
    font-size: 14px;
    color: #333;
    margin-bottom: 12px;
    font-weight: 500;
  }

  /* 添加滚动条样式 */
  .selected-file-list::-webkit-scrollbar,
  .folder-tree::-webkit-scrollbar {
    width: 4px;
    height: 4px;
  }

  .selected-file-list::-webkit-scrollbar-thumb,
  .folder-tree::-webkit-scrollbar-thumb {
    background: #d9d9d9;
    border-radius: 2px;
  }

  .selected-file-list::-webkit-scrollbar-track,
  .folder-tree::-webkit-scrollbar-track {
    background: #f5f5f5;
  }

  .tree-node {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .folder-icon {
    width: 16px;
    height: 16px;
  }

  .folder-name {
    font-size: 13px;
    color: #333;
  }

  :deep(.ant-tree-node-content-wrapper:hover) {
    background-color: #e6f4ff;
  }

  :deep(.ant-tree-node-selected) {
    background-color: #e6f4ff !important;
  }

  /* 滚动条美化 */
  .folder-tree::-webkit-scrollbar,
  .files-table :deep(.ant-table-body)::-webkit-scrollbar {
    width: 4px;
    height: 4px;
  }

  .folder-tree::-webkit-scrollbar-thumb,
  .files-table :deep(.ant-table-body)::-webkit-scrollbar-thumb {
    background: #d9d9d9;
    border-radius: 2px;
  }

  .folder-tree::-webkit-scrollbar-track,
  .files-table :deep(.ant-table-body)::-webkit-scrollbar-track {
    background: #f5f5f5;
  }

  .search-icon {
    width: 14px;
    height: 14px;
    opacity: 0.6;
  }

  :deep(.ant-input-prefix) {
    margin-right: 4px;
  }

  /* 调整图标样式 */
  :deep(.anticon) {
    font-size: 14px;
  }

  :deep(.ant-btn-link .anticon) {
    font-size: 16px;
    opacity: 0.6;
  }

  :deep(.ant-btn-link:hover .anticon) {
    opacity: 1;
  }

  :deep(.ant-input-prefix .anticon) {
    margin-right: 4px;
    color: rgba(0, 0, 0, 0.45);
  }

  .file-name-text {
    cursor: pointer;
    color: var(--theme-text);
    transition: all 0.3s;
    display: inline-block;
    padding: 8px 0;
  }

  .file-name-text:hover {
    color: var(--theme-primary);
    text-decoration: underline;
  }

  .files-title {
    font-size: 18px;
    font-weight: 500;
    color: var(--theme-text);
    margin: 16px 0;
    padding: 0 16px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    line-height: 32px;
    transition: color 0.3s ease;
  }

  .path-separator {
    margin: 0 8px;
    color: var(--theme-textSecondary);
    font-size: 14px;
    font-weight: normal;
    transition: color 0.3s ease;
  }

  .folder-path-item {
    color: var(--theme-textSecondary);
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;
    font-weight: normal;
  }

  .folder-path-item:hover {
    color: var(--theme-primary);
    text-decoration: underline;
  }

  .share-file-info {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px;
    background: var(--theme-surface);
    border: 1px solid var(--theme-border);
    border-radius: 8px;
    transition: all 0.3s ease;

    .file-icon {
      flex-shrink: 0;
      margin-right: 12px;
      width: 24px;
      height: 24px;
      display: flex;
      align-items: center;

      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .file-name {
      flex: 1;
      font-size: 14px;
      color: var(--theme-text);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      transition: color 0.3s ease;
      font-weight: 500;
    }
  }

  .share-code-type {
    margin-bottom: 12px;
  }

  .share-success-modal {
    :deep(.ant-modal-content) {
      padding: 0;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
      width: 800px !important;
      background: var(--theme-background);
    }

    :deep(.ant-modal) {
      width: 800px !important;
    }

    .share-success-content {
      padding: 24px;
      background: var(--theme-background);

      .file-info-section {
        display: flex;
        align-items: center;
        background: var(--theme-surface);
        padding: 12px;
        border-radius: 4px;
        margin-bottom: 20px;
        border: 1px solid var(--theme-border);

        .file-icon {
          width: 32px;
          height: 32px;
          flex-shrink: 0;
          margin-right: 12px;
          display: inline-flex;
          align-items: center;
          justify-content: center;

          img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
          }
        }

        .file-name {
          flex: 1;
          font-size: 14px;
          color: var(--theme-text);
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          display: inline-block;
          font-weight: 500;
        }
      }

      .share-info-list {
        .share-info-item {
          display: flex;
          align-items: center;
          margin-bottom: 16px;
          padding: 12px;
          background: var(--theme-surface);
          border-radius: 6px;
          border: 1px solid var(--theme-border);

          .info-label {
            width: 80px;
            color: var(--theme-text);
            flex-shrink: 0;
            font-weight: 600;
            font-size: 14px;
          }

          .info-value {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 0;

            .text-content {
              flex: 1;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              color: var(--theme-text);
              font-size: 14px;
              font-weight: 500;
            }

            .copy-btn {
              flex-shrink: 0;
              margin-left: 8px;
              padding: 0 8px;
              color: var(--theme-primary);
            }

            .copy-btn:hover {
              color: var(--theme-secondary);
            }

            span {
              color: var(--theme-text);
              font-size: 14px;
              font-weight: 500;
            }
          }
        }
      }
    }

    .share-success-header {
      background: linear-gradient(135deg, var(--theme-primary), var(--theme-secondary));
      padding: 20px;
      text-align: center;
      color: white;

      .success-icon {
        font-size: 32px;
        margin-bottom: 8px;
        animation: zoomIn 0.3s ease-out;
        color: white;
      }

      .success-text {
        font-size: 18px;
        font-weight: 600;
        display: block;
        color: white;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
      }
    }

    .share-success-footer {
      text-align: center;
      padding: 0 24px 24px;
      background: var(--theme-background);

      .ant-btn-primary {
        background: var(--theme-primary);
        border-color: var(--theme-primary);
        color: white;
        height: 40px;
        padding: 0 24px;
        font-size: 16px;
        font-weight: 500;
        border-radius: 6px;
      }

      .ant-btn-primary:hover {
        background: var(--theme-secondary);
        border-color: var(--theme-secondary);
      }
    }
  }

  @keyframes zoomIn {
    from {
      opacity: 0;
      transform: scale(0.5);
    }
    to {
      opacity: 1;
      transform: scale(1);
    }
  }

  /* 上传列表样式 */
  .upload-list {
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
  }

  .upload-list-header {
    padding: 12px 16px;
    border-bottom: 1px solid #eee;
    font-size: 14px;
    font-weight: 500;
  }

  .upload-list-header .tips {
    font-size: 12px;
    color: #999;
    margin-left: 8px;
    font-weight: normal;
  }

  .upload-list-content {
    max-height: 400px;
    overflow-y: auto;
  }

  .upload-item {
    padding: 12px 16px;
    border-bottom: 1px solid #eee;
  }

  .upload-item:last-child {
    border-bottom: none;
  }

  .upload-item .file-name {
    font-size: 14px;
    margin-bottom: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .upload-item .upload-status {
    display: flex;
    align-items: center;
    margin-top: 8px;
    font-size: 13px;
  }

  .status-init {
    color: #909399;
  }

  .status-uploading {
    color: #409eff;
  }

  .status-success {
    color: #67c23a;
  }

  .status-error {
    color: #f56c6c;
  }

  .upload-status .ant-btn-link {
    margin-left: 12px;
    padding: 0;
  }

  .empty-tip {
    padding: 32px;
    text-align: center;
    color: #909399;
    font-size: 14px;
  }

  /* 滚动条样式 */
  .upload-list-content::-webkit-scrollbar {
    width: 4px;
    height: 4px;
  }

  .upload-list-content::-webkit-scrollbar-thumb {
    background: #d9d9d9;
    border-radius: 2px;
  }

  .upload-list-content::-webkit-scrollbar-track {
    background: #f5f5f5;
  }

  /* 新建文件夹弹窗样式 */
  .new-folder-modal {
    :deep(.ant-modal-content) {
      border-radius: 12px;
      overflow: hidden;
    }

    :deep(.ant-modal-header) {
      padding: 16px 24px;
      border-bottom: 1px solid #f0f0f0;

      .ant-modal-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }
    }

    :deep(.ant-modal-body) {
      padding: 24px;
    }

    :deep(.ant-modal-footer) {
      padding: 16px 24px;
      border-top: 1px solid #f0f0f0;

      .ant-btn {
        border-radius: 6px;
        height: 36px;
        padding: 0 16px;
        font-size: 14px;
      }
    }
  }

  .new-folder-content {
    .folder-icon-wrapper {
      text-align: center;
      margin-bottom: 16px;

      .folder-icon {
        width: 48px;
        height: 48px;
        object-fit: contain;
      }
    }

    .folder-input {
      height: 40px;
      font-size: 14px;
      border-radius: 6px;

      &:hover,
      &:focus {
        border-color: #40a9ff;
        box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
      }
    }

    :deep(.ant-form-item) {
      margin-bottom: 0;
    }

    :deep(.ant-input-show-count-suffix) {
      color: #999;
    }
  }

  .custom-share-input {
    display: flex;
    align-items: center;
    margin-top: 8px;
    margin-left: 16px;

    .share-code-input {
      width: 120px;
      height: 32px;
      padding: 4px 11px;
      border: 1px solid var(--theme-border);
      border-radius: 6px;
      margin-right: 8px;
      background: var(--theme-surface);
      color: var(--theme-text);
      font-size: 14px;
      transition: all 0.3s ease;
    }

    .share-code-input:focus {
      outline: none;
      border-color: var(--theme-primary);
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
    }

    .share-code-input::placeholder {
      color: var(--theme-textSecondary);
    }

    .input-count {
      font-size: 12px;
      color: var(--theme-textSecondary);
    }
  }
</style>
